package com.atguigu.yygh.gateway.filter;

import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author mgx
 * @version 1.0
 * @description: 鉴权
 * @date 2022/8/29 16:46
 */
//@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    // 创建一个ant风格的匹配器
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象
        // 此时获取到的是ServerHttpRequest: springmvc: webFlux
        // HttpServletRequest: -> springmvc: servlet
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        String path = request.getURI().getPath();
        if(antPathMatcher.match("/admin/user/**", path)) { // 如果请求的是登录接口，就放行
            return chain.filter(exchange);
        }else { // 请求的是别的接口，需要进行拦截
            // 获取请求头中是否有X-token
            List<String> tokenList = request.getHeaders().get("X-Token");
            if(tokenList == null) {
                // 表示没有token，返回拦截数据
                // 获取响应对象
                ServerHttpResponse response = exchange.getResponse();
                // response.setStatusCode(HttpStatus.UNAUTHORIZED);

                // 路由跳转配套使用
                response.setStatusCode(HttpStatus.SEE_OTHER);
                // 如果没有token，就跳转到登录页面
                response.getHeaders().set(HttpHeaders.LOCATION, "http://localhost:9528");
                return response.setComplete(); // 完成响应
            }else {
                // 有token，直接放行
                return chain.filter(exchange);
            }
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
